<script lang="ts" setup>
import type { TreeProps } from 'ant-design-vue';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Card, message, Tree } from 'ant-design-vue';

import { getMenuListApi } from '#/api/system/menu';
import { getRoleByIdApi, grantMenuApi } from '#/api/system/role';
import { toTree } from '#/utils';

const menuTreeData = ref<TreeProps['treeData']>();
const roleId = ref(0);
const checkedKeys = ref<number[]>([]);

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    await grantMenuApi(roleId.value, checkedKeys.value);
    message.success('菜单授权成功');
    drawerApi.close();
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { id, name } = drawerApi.getData<Record<string, any>>();
      roleId.value = id;
      drawerApi.setState({ title: `分配菜单 (${name})` });

      const role = await getRoleByIdApi(id);
      checkedKeys.value = role.roleMenus?.map((m) => m.menuId) ?? [];

      // 查询菜单
      const menus = await getMenuListApi();
      menuTreeData.value = toTree(menus);
    }
  },
  title: '分配菜单',
});
</script>

<template>
  <Drawer>
    <Card>
      <Tree
        v-model:checked-keys="checkedKeys"
        :default-expand-all="true"
        :field-names="{ key: 'id', title: 'title', children: 'children' }"
        :tree-data="menuTreeData"
        checkable
      />
    </Card>
  </Drawer>
</template>
